package online.inote.naruto.utils.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.List;

/**
 * @description 默认结果转换器
 * @author gaopengsui@creditease.cn
 * @date 2021/10/08 7:43 下午
 */
public class DefaultResultConvertor implements ResultConvertor {

  /**
   * 转换映射
   *
   * @param resultBody 返回结果
   * @return 转换后结果
   */
  @Override
  public String mapping(String resultBody) {
    return resultBody;
  }

  /**
   * Bean转换
   *
   * @param type 类型
   * @param in 输入数据
   * @param charset 字符设置
   * @return Bean
   */
  @Override
  public <T> T toBean(Type type, InputStream in, Charset charset) {
    return JSON.parseObject(mapping(toString(in, charset)), type, new Feature[0]);
  }

  /**
   * 转换为List
   *
   * @param type 类型
   * @param in 输入数据
   * @param charset 字符设置
   * @return List集合
   */
  @Override
  public <T> List<T> toList(Class<T> type, InputStream in, Charset charset) {
    return JSON.parseArray(mapping(this.toString(in, charset)), type);
  }

  protected String toString(InputStream in, Charset charset) {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    byte[] buff = new byte[512];

    int len;
    try {
      while ((len = in.read(buff)) > 0) {
        output.write(buff, 0, len);
      }
    } catch (IOException var7) {
      throw new IllegalStateException(var7);
    }

    try {
      return output.toString(charset.name());
    } catch (UnsupportedEncodingException var6) {
      throw new IllegalStateException(var6);
    }
  }
}
